//
//  AsynchronousLoadingImageView.m
//  TestTable
//
//  Created by Hunk on 11-3-21.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "AsyncLoadingImageView.h"
#import "SDWebImageManager.h"

#define TAG_DEFAULTIMAGEVIEW 10     // NOT 0 & 1
#define TAG_ACTIVITYINDICATORVIEW 11

#define DELAYTIME (20.0)

@implementation AsyncLoadingImageView

- (void)loadImageFromURLString:(NSString*)urlString placeholderImage:(UIImage*)placeholderImage
{
    // Add default image
	UIImageView* defaultImageView = [[[UIImageView alloc] initWithFrame:self.bounds] autorelease];
    [defaultImageView setBackgroundColor:[UIColor clearColor]];
    UIImage *image = [UIImage imageNamed:@""];
    if(!image)
    {
        [defaultImageView setBackgroundColor:[UIColor blackColor]];
    }
    else
    {
        [defaultImageView setImage:image];
    }
	defaultImageView.tag = TAG_DEFAULTIMAGEVIEW;
	[self addSubview:defaultImageView];
    
    // Add activityIndicatorView
	activityIndicatorView = [[[UIActivityIndicatorView alloc] initWithFrame:
                              CGRectMake((self.frame.size.width - 25.0)/2, 
                                         (self.frame.size.height - 25.0)/2, 
                                         25.0, 
                                         25.0)] autorelease];
	activityIndicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
	activityIndicatorView.tag = TAG_ACTIVITYINDICATORVIEW;
	[activityIndicatorView startAnimating];
	[self addSubview:activityIndicatorView];
    
    // 如果TimeOut那么需要停止activityIndicator　animating
    [self performSelector:@selector(loadImageFailed:) withObject:nil afterDelay:DELAYTIME];
    
    SDWebImageManager* manager = [SDWebImageManager sharedManager];
    [manager cancelForDelegate:self];
    if(urlString)
    {   
        [manager downloadWithURL:[NSURL URLWithString:urlString] delegate:self];
    }
}

- (void)cancelCurrentImageLoad
{
    [[SDWebImageManager sharedManager] cancelForDelegate:self];
}

- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image
{
    UIImageView* defaultImageView = (UIImageView*)[self viewWithTag:TAG_DEFAULTIMAGEVIEW];
    [defaultImageView removeFromSuperview];
    
    UIImageView* imageView = [[[UIImageView alloc] initWithImage:image] autorelease];
    [self addSubview:imageView];
    imageView.frame = self.bounds;
    [imageView setNeedsLayout];
    [self setNeedsLayout];
    
    if(activityIndicatorView.isAnimating)
	{
		[activityIndicatorView stopAnimating];
	}
}

- (UIImage*)getImage 
{
    NSArray *imageArray = [self subviews];
    
    if(imageArray && [imageArray count] != 0)
    {
        UIImageView* imageView = [imageArray objectAtIndex:1];
    
        return [imageView image];
    }
    
    return nil;
}

#pragma mark -
#pragma mark loadImageFailed
- (void)loadImageFailed:(id)sender
{
    if(activityIndicatorView.isAnimating)
	{
		[activityIndicatorView stopAnimating];
	}
}

@end
